package br.com.winesys.geta.persistence.hibernate;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.type.NullableType;
import org.hibernate.type.TypeFactory;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;

public class BooleanEnumUserType implements UserType, ParameterizedType {

	private static final String DEFAULT_TRUE_VALUE = "T";
	private static final String DEFAULT_FALSE_VALUE = "F";

	private NullableType type;
	private int[] sqlTypes;
	private String trueValue;
	private String falseValue;

	@Override
	public void setParameterValues(Properties parameters) {
		this.trueValue = parameters.getProperty("trueValue", BooleanEnumUserType.DEFAULT_TRUE_VALUE);
		this.falseValue = parameters.getProperty("falseValue", BooleanEnumUserType.DEFAULT_FALSE_VALUE);

		this.type = (NullableType) TypeFactory.basic(String.class.getName());
		this.sqlTypes = new int[] { this.type.sqlType() };
	}

	@Override
	public Class<Boolean> returnedClass() {
		return Boolean.class;
	}

	@Override
	public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
		final Object identifier = this.type.get(rs, names[0]);
		if (identifier == null) {
			return null;
		}
		return (identifier.toString().equalsIgnoreCase(this.trueValue));

	}

	@Override
	public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
		if (value == null) {
			st.setNull(index, this.type.sqlType());
		} else if (value.equals(Boolean.TRUE)) {
			this.type.set(st, this.trueValue, index);
		} else {
			this.type.set(st, this.falseValue, index);
		}
	}

	@Override
	public int[] sqlTypes() {
		return this.sqlTypes;
	}

	@Override
	public Object assemble(Serializable cached, Object owner) throws HibernateException {
		return cached;
	}

	@Override
	public Object deepCopy(Object value) throws HibernateException {
		return value;
	}

	@Override
	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable) value;
	}

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		return x.equals(y);
	}

	@Override
	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}

	@Override
	public boolean isMutable() {
		return false;
	}

	@Override
	public Object replace(Object original, Object target, Object owner) throws HibernateException {
		return original;
	}
}